import axios from "axios";
import qs from "qs";
import config from "../../config.json";

const BASE_URL = config.service_base_path;
const DEFAULT_TIME_OUT = 10000;

export default {
    initialize: () => {
        axios.defaults.baseURL = BASE_URL;
        axios.defaults.timeout = DEFAULT_TIME_OUT;
        axios.defaults.headers.common = {
            "Accept": "application/json",
            "Authorization": "Bearer ",
            "X-Requested-With": "XMLHttpRequest"
        };
        axios.interceptors.response.use(res => {
          if(!res){
            return;
          }
          //没登录

          if (res.status === 200) {
              if(res.data.error){
                if(res.data.error.code === 99980001){
                  this.$message.error(res.data.error.message);

                }
                 if(res.data.error.code==10010002){
          	         window.location.href = `${config.ui_base_path}`;
                     }

              }
            if(res.data.code==10010002){
              window.location.href = `${config.ui_base_path}`;
            }
              return Promise.resolve(res.data);
            }

            // if (res.data.status === -2) {
            //     window.location.href = `${config.ui_base_path}login`;
            //     res.data.msg = "session过期或者没有登录";
            // }
            const responseError = new Error(res.data.msg);
            responseError.origin = res.data;
            return Promise.reject(responseError);
        }, error => {
          //没登录
          if(res.data.code==10010002){
            window.location.href = `${config.ui_base_path}`;
          }
          console.log(error);
          // let responseError;
          if (error.response.status === 500) {
                responseError = new Error("服务器内部错误，请稍后重试或与管理员联系");
            } else {
                responseError = new Error("消息发送失败，请稍后重试或与管理员联系");
            }
            responseError.error = error;
            return Promise.reject(responseError);
            return Promise.reject(error);
        });
        axios.interceptors.request.use((config) => {
            if (config.method === "get") {
                return config;
            }

            config.data = qs.stringify(config.data);
            return config;
        }, (error) => {
            return Promise.reject(error);
        });
    }
};
